<?php

declare(strict_types=1);

namespace App\Robot\Crontab;

use App\Common\Robot\Robot;
use App\CustHub\Constants\FrdCircTaskSendStatusConstants;
use App\CustHub\Mapper\ChRobotMapper;
use App\CustHub\Model\ChFriendCircleTaskSendRecord;
use Hyperf\Coroutine\Coroutine;
use function Hyperf\Coroutine\co;

/**
 * 定时删除朋友圈
 */
class FriendCircleCrontab
{
    public function execute(): string
    {
        $list = ChFriendCircleTaskSendRecord::query()
            ->where('friend_circle_status',1)
            ->where('timing_delete_switch',1)
            ->where('timing_delete_time','<',time())
            ->get();
        co(function () use ($list){
            $robotMapper = container()->get(ChRobotMapper::class);
            foreach ($list as $item){
                $robotInfo = $robotMapper->findById($item->robot_id);
                if(!empty($robotInfo) && $robotInfo->login_status == 1){
                    $robotService = make(Robot::class,[$robotInfo->server_id,$robotInfo->uuid])->gateway();
                    $response = $robotService->deleteSns((int)$item->sns_id);
                    if($response === false){
                        logger()->info("删除朋友圈失败recordId:".$item->id.'-'.$robotService->getErrorMsg());
                        continue;
                    }
                    ChFriendCircleTaskSendRecord::query()
                        ->where('id',$item->id)
                        ->update([
                            'friend_circle_status' => FrdCircTaskSendStatusConstants::DELETE
                        ]);
                    logger()->info("删除朋友圈成功recordId:".$item->id);
                }
                Coroutine::sleep(rand(2,5));
            }
        });


        return 'successfully';
    }
}